<template>
  <BasicModal v-bind="$attrs" @register="registerModal" showFooter :title="getTitle" width="50%">
    <div class="carOne">
      <BasicForm @register="registerForm" />
      <div class="content">
        <div class="role">
          <div class="text">权限分配</div>
          <div class="steps">
            <Steps :current="current" :items="items" size="small"></Steps>
          </div>
        </div>
        <!-- 功能权限 --- start -->
        <div class="menu" v-show="current == 0">
          <Tree size="small" :disabled="isLook" :checkStrictly="true" ref="treeRef" v-if="menuList.length"
            defaultExpandAll v-model:selectedKeys="selectedKeys" @check="checkKeys" v-model:checkedKeys="checkedKeys"
            checkable :tree-data="menuList" @click.prevent :fieldNames="fieldNames">
            <!-- <template #title="data">
              <div @click.stop>
                {{ data.name }}
                <CheckboxGroup
                  v-if="data.checkboxValue"
                  :disabled="isLook"
                  v-model:value="data.checkboxValue.value"
                  @change="changes"
                  :options="data.checkboxOptions"
                >
                </CheckboxGroup>
              </div>
            </template> -->
          </Tree>
        </div>
        <!-- 功能权限 --- end -->
        <!-- 数据权限 --- start-->
        <div class="menu" v-show="current == 1">
          <!-- 地图&&区域权限 start -->
          <div class="warning_map_area">
            <span>地图和区域数据</span>
            <Tree size="small" :disabled="isLook" :checkStrictly="true" v-if="mapAuthList.length"
              v-model:selectedKeys="selectedMapKeys" v-model:checkedKeys="checkedMapKeys" checkable
              :tree-data="mapAuthList" @click.prevent :fieldNames="fieldNamesMap">
            </Tree>
          </div>
          <!-- 地图&&区域权限 end -->
          <!-- 告警权限 start-->
          <div class="warning_auth">
            <span>告警数据</span>
            <Tree size="small" :disabled="isLook" :checkStrictly="true" v-if="alarmAuthList.length"
              v-model:selectedKeys="selectedAlarmKeys" v-model:checkedKeys="checkedAlarmKeys" checkable
              :tree-data="alarmAuthList" @click.prevent :fieldNames="fieldNamesCode">
            </Tree>
          </div>
          <!-- 告警权限 end-->
        </div>
        <!-- 数据权限 --- end-->
      </div>
    </div>
    <template #footer>
      <Button @click="closeModal">取 消</Button>

      <Button type="text" v-if="current == 1" @click="prev">上 一 步</Button>

      <Button type="primary" v-if="current == 0" @click="next">下 一 步</Button>

      <Button type="primary" v-if="current == 1" @click="handleSubmit" :disabled="isLook">提 交</Button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { formSchema } from './index.data';
import { BasicModal, useModalInner } from '@/components/Modal';
import { Steps, Tree, CheckboxGroup, Button } from 'ant-design-vue';
import { saveOrUpdateMenu, getRoleMenu, getRoleAlarm, getRoleMap } from '@/api/system/role';
import { list } from '@/api/system/menu';

import { useMessage } from '@/hooks/web/useMessage';
import { Iresult } from '#/axios';

const treeRef = ref(null)

defineOptions({ name: 'Modal' });

const fieldNames = {
  children: 'children',
  title: 'name',
  key: 'id',
};

const fieldNamesCode = {
  children: 'children',
  title: 'name',
  key: 'code',
};
const fieldNamesMap = {
  children: 'areas',
  title: 'name',
  key: 'id',
};

const items = [
  {
    key: 'func',
    title: '功能权限',
  },
  {
    key: 'data',
    title: '数据权限',
  },
  {
    key: '',
    title: '',
    status: 'finish',
  },
];

const current = ref<number>(0);

const { createMessage: msg } = useMessage();

const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);
const isLook = ref(true);

const menuList = ref([]);
const alarmAuthList = ref([]);
const mapAuthList = ref([]);

const selectedKeys = ref<string[]>([]);
const checkedKeys = ref<string[]>([]);
const selectedAlarmKeys = ref<string[]>([]);
const checkedAlarmKeys = ref<string[]>([]);
const selectedMapKeys = ref<string[]>([]);
const checkedMapKeys = ref<string[]>([]);
const authListkeys = ref<string[]>([]);
const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

const [registerForm, { resetFields, setFieldsValue, validate, setProps }] = useForm({
  labelWidth: 140,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

const next = () => {
  current.value++;
};
const prev = () => {
  current.value--;
};

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    let idaa = getCheckboxValue(menuList.value);
    checkedKeys.value = Array.isArray(checkedKeys.value)
      ? checkedKeys.value
      : checkedKeys.value.checked;
    let ids = [...checkedKeys.value];
    values.resourceIds = ids;
    checkedMapKeys.value = Array.isArray(checkedMapKeys.value)
      ? checkedMapKeys.value
      : checkedMapKeys.value.checked;
    let idaaMap = getCheckboxValue(mapAuthList.value);
    let idsMap = [...checkedMapKeys.value, ...idaaMap];
    values.mapIds = idsMap;
    let idaaAlarm = getCheckboxValue(alarmAuthList.value);
    checkedAlarmKeys.value = Array.isArray(checkedAlarmKeys.value)
      ? checkedAlarmKeys.value
      : checkedAlarmKeys.value.checked;
    let idsAlarm = [...checkedAlarmKeys.value, ...idaaAlarm];
    values.warnTypeCodes = idsAlarm;
    const res = await saveOrUpdateMenu(values, !!values.id);
    if (res.isSucceed) {
      msg.success('操作成功');
      closeModal();
      emit('success');
    }
  } finally {
    setModalProps({ confirmLoading: false });
  }
}

let getCheckboxValue = (data) => {
  let arr = [];
  let func = (cld) => {
    for (let i = 0; i < cld.length; i++) {
      let item: any = cld[i];
      if (!item.children) return;
      if (item.children[0] && item.children[0].menuType === 2) {
        for (let j = 0; j < item.checkboxValue.length; j++) {
          arr.push(item.checkboxValue[j]);
        }
      } else {
        func(item.children);
      }
    }
  };
  func(data);

  return arr;
};

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setProps({ disabled: data.isLook });
  isLook.value = !!data.isLook;
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  current.value = 0;
  checkedKeys.value = [];
  authListkeys.value = [];
  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.record,
    });
  }

  const roleAlarmResult = await getRoleAlarm({});

  alarmAuthList.value = roleAlarmResult.data;

  const roleMapsResult = await getRoleMap({});

  mapAuthList.value = roleMapsResult.data;

  if (data.record) {
    const roleMenuResult = await getRoleMenu(data.record.id);

    checkedKeys.value = roleMenuResult.data.menuIds;
    selectedAlarmKeys.value = roleMenuResult.data.warnTypeCodes;
    checkedAlarmKeys.value = roleMenuResult.data.warnTypeCodes;
    authListkeys.value = roleMenuResult.data.menuIds;
    selectedMapKeys.value = roleMenuResult.data.mapIds;
    checkedMapKeys.value = roleMenuResult.data.mapIds;
  }

  function checkKeys(keys: any, e: any) {
    let arr = keys.concat(e.halfCheckedKeys)
  }

  const treeData = (await list({})) as Iresult;

  await extractCheckboxOptions(treeData.data);
  menuList.value = treeData.data as [];
  function extractCheckboxOptions(data) {
    // 如果数据为空或不是数组，则返回空数组
    if (!data || !Array.isArray(data)) {
      return [];
    }
    for (let i = 0; i < data.length; i++) {
      let item = data[i];
      if (item.children[0] && item.children[0].menuType === 2) {
        let arr = item.children
          .filter((item) => {
            let r = authListkeys.value.find((x) => x === item.id);
            if (r) {
              return r;
            }
          })
          .map((x) => x.id);
        item.checkboxValue = item.checkboxValue || ref(arr);
        item.checkboxOptions = item.children.map((x) => {
          return {
            value: x.id,
            label: x.name,
            menuType: x.menuType,
          };
        });
      } else {
        extractCheckboxOptions(item.children);
      }
    }
  }
});
</script>

<style lang="scss" scoped>
.menu {
  width: 100%;
  height: 300px;
  max-height: 300px;
  overflow: auto;

  .menu-item {
    margin: 10px 0;
  }

  .menu-cgkd {
    padding-bottom: 10px;
    border-bottom: 1px solid #f9f4f4;
  }

  ::v-deep .ant-checkbox-group {
    display: initial !important;
  }

  ::v-deep .ant-tree-title {
    display: flex;
    align-items: center;
    width: 100%;
    white-space: nowrap;

    .ant-checkbox-group {
      margin-left: 20px;
    }
  }
}

.role {
  display: flex;
  align-items: center;
  width: 90%;
  margin: 20px 5%;

  .text {
    width: 100px;
    color: #4585d8;
    font-size: 15px;
    font-weight: 600;
  }

  .steps {
    flex: 1;
  }
}
</style>
